package org.example.interncandidate.service.login.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.aspectj.weaver.patterns.IToken;
import org.example.interncandidate.exception.AssertionException;
import org.example.interncandidate.mapper.login.LoginMapper;
import org.example.interncandidate.model.image.po.Image;
import org.example.interncandidate.model.person.dto.LoginRequestDTO;
import org.example.interncandidate.model.person.po.PersonInfo;
import org.example.interncandidate.model.person.po.PersonToken;
import org.example.interncandidate.model.person.vo.PersonInfoVO;
import org.example.interncandidate.service.Redis.Impl.RedisImageServiceImpl;
import org.example.interncandidate.service.Redis.Impl.RedisTokenServiceImpl;
import org.example.interncandidate.service.login.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class LoginServiceImpl extends ServiceImpl<LoginMapper, PersonInfo> implements LoginService{
    @Autowired
    private LoginMapper loginMapper;
    @Autowired
    private RedisTokenServiceImpl redisTokenService;
    @Autowired
    private RedisImageServiceImpl redisImageService;
    @Override
    public PersonInfoVO login(LoginRequestDTO loginRequest) {
        if (loginRequest==null) throw new AssertionException(400,"用户名和密码不能为空！");
        PersonInfo personInfo = loginMapper.selectOne(new LambdaQueryWrapper<PersonInfo>()
                .eq(PersonInfo::getUsername, loginRequest.getUsername())
                .eq(PersonInfo::getPassword, loginRequest.getPassword()));
        if (personInfo==null) throw new AssertionException(400,"用户名或密码错误");
        if (!redisImageService.isValidByImage(new Image(loginRequest.getUid(),loginRequest.getCode())))
            throw new AssertionException(400,"验证码错误！");
        redisTokenService.saveTokenByRedis(new PersonToken(personInfo.getId()));
        String token = redisTokenService.getPersonTokenById(personInfo.getId());
        return new PersonInfoVO(token,personInfo);
    }
}
